package home.ybubnov.bugcrss;

import home.ybubnov.bugcrss.entity.WebPage;
import home.ybubnov.bugcrss.entity.Update;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.servlet.ServletException;
import javax.servlet.http.*;

import com.google.appengine.api.datastore.Text;
import com.sun.syndication.feed.synd.SyndContent;
import com.sun.syndication.feed.synd.SyndContentImpl;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndEntryImpl;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.feed.synd.SyndFeedImpl;
import com.sun.syndication.io.SyndFeedOutput;

@SuppressWarnings("serial")
public class BUGCRSSServlet extends HttpServlet {

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		EntityManager em = EMF.emf.createEntityManager();
		try {
			em.getTransaction().begin();
			WebPage page = null;
			List<WebPage> results= (List<WebPage>)em.createNamedQuery("WebPage.getWebPage").getResultList();
			if (results.size() > 0){
				page = results.get(0);
			}else{
				return;
			}
			
			SyndFeed feed = new SyndFeedImpl();
			feed.setFeedType("atom_1.0");
			feed.setTitle("The Boston-area User Group Calendar");
			feed.setLink("http://www.bugc.org/");

			List<SyndEntry> entries = new ArrayList<SyndEntry>();
			SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd h:mm a");
			for(Update update : page.getUpdates()){
				SyndEntry entry = new SyndEntryImpl();
				entry.setTitle("New Events at "+format.format(update.getDate()));
				entry.setPublishedDate(update.getDate());

				SyndContent content = new SyndContentImpl();
				content.setType("text/html");
				content.setValue(update.getTextAsString());
				entry.setContents(Arrays.asList(content));
				
				entries.add(entry);
			}
			

			feed.setEntries(entries);
			SyndFeedOutput output = new SyndFeedOutput();

			output.output(feed, resp.getWriter());
			em.getTransaction().commit();
		} catch (Exception e) {
			if (em.getTransaction().isActive()) {
				em.getTransaction().rollback();
			}
			throw new RuntimeException(e);
		}finally{
			em.close();
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}
}
